//
//  YJUserAccount.swift
//  YJWeiBo
//
//  Created by Jim1024 on 2017/1/12.
//  Copyright © 2017年 Jim1024. All rights reserved.
//

import UIKit

// 对象归档需要实现NSCoding
class YJUserAccount: NSObject, NSCoding {

    var access_token: String?
    
    /// access_token的生命周期，单位是秒数
    // 基本数据类型作为属性不能为可选,使用一个默认值
    var expires_in: TimeInterval = 0 {
        didSet {
            expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    
    /// 过期时间,expires_in转成系统的NSDate,expires_in是Double不好来判断过期时间,转成NSDate比较好判断过期时间
    var expiresDate: Date?
    
    var uid: String?
    /// 用户名称
    var screen_name: String?
    
    /// 用户头像地址
    var avatar_large: String?
    
    // 重载构造函数 Swift 中支持函数重载，同样的函数名，不一样的参数类型
    init(_ dict: [String : Any]) {
        // 没有在super.init()之前给属性赋值,属性需要定义为可选
        super.init()
        
        // 使用KVC赋值
        setValuesForKeys(dict)
    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        JPrint("undefineKey: \(key)")
    }
    
    override var description: String {
        get {
            let keys = ["access_token", "expires_in", "expiresDate", "uid"]
            // 拿着传入的key去模型中找对应的属性,找到属性的值后会将key和属性的值,拼接成字典
            return dictionaryWithValues(forKeys: keys).description
        }
    }
    
    func encode(with aCoder: NSCoder) {
        aCoder.encode(access_token, forKey: "access_token")
        aCoder.encode(expires_in, forKey: "expires_in")
        aCoder.encode(expiresDate, forKey: "expiresDate")
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(screen_name, forKey: "screen_name")
        aCoder.encode(avatar_large, forKey: "avatar_large")
    }
    
    // NSCoding 的这个 init?(coder aDecoder: NSCoder) 是需要为指定构造函数,在"extension"中的构造函数只能是便利构造函数
    required init?(coder aDecoder: NSCoder) {
        super.init()
        access_token = aDecoder.decodeObject(forKey: "access_token") as? String
        expires_in = aDecoder.decodeDouble(forKey: "expires_in")
        expiresDate = aDecoder.decodeObject(forKey: "expiresDate") as? Date
        uid = aDecoder.decodeObject(forKey: "uid") as? String
        screen_name = aDecoder.decodeObject(forKey: "screen_name") as? String
        avatar_large = aDecoder.decodeObject(forKey: "avatar_large") as? String
    }
}
